package util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.XMLConstants;
import javax.xml.transform.Source;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author aptech
 */
public class SaxValidator {
    public static void main(String[] args) {
        try {
            InputSource is = new InputSource(new BufferedReader(new FileReader("student.xml")));
            SchemaFactory sFac = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            Source schemaFile = new StreamSource(new File("student.xsd"));
            Schema schema = null;
            try {
                schema = sFac.newSchema(schemaFile);
            } catch (SAXException ex) {
                Logger.getLogger(SaxValidator.class.getName()).log(Level.SEVERE, null, ex);
            }
            Validator validator = schema.newValidator();
            try {
                validator.validate(new SAXSource(is));
                System.out.println("Document is valid hehe");
            } catch (SAXException ex) {
                Logger.getLogger(SaxValidator.class.getName()).log(Level.SEVERE, null, ex);
                System.out.println("invalid");
            } catch (IOException ex) {
                Logger.getLogger(SaxValidator.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(SaxValidator.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
